package com.heer.gymnasium.activity;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.heer.amap.utils.ToastUtil;
import com.heer.api.ResponseData.ApiResponse;
import com.heer.api.callback.BaseCallback;
import com.heer.api.sign.SignHelper;
import com.heer.gymnasium.R;
import com.heer.gymnasium.util.ActivityStartUtils;
import com.heer.gymnasium.util.Session;
import com.heer.gymnasium.util.StringUtils;
import com.heer.gymnasium.util.SystemUtils;
import com.heer.model.LoginBean;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by heer on 17/3/28.
 */

public class LoginActivity extends BaseActivity {
    @BindView(R.id.image_logo)
    ImageView imageLogo;
    @BindView(R.id.btn_visible)
    ImageView btnVisible;
    @BindView(R.id.edit_account)
    EditText editAccount;
    @BindView(R.id.edit_password)
    EditText editPassword;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.btn_forget_password)
    TextView btnForgetPassword;
    @BindView(R.id.btn_register)
    Button btnRegister;
    @BindView(R.id.btn_wx_login)
    ImageView btnWxLogin;

    private IWXAPI api;
    public static Handler mHandler;
    private String mUnionId;
    @Override
    protected void init() {
        super.init();
        setContentView(R.layout.activity_login_1);
    }

    @Override
    protected void initView() {
        super.initView();
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorPrimaryDark)));
        titleBuilder.setTitleText("登录");
        titleBuilder.setLeftImage(0);
        titleBuilder.setBackground(Color.TRANSPARENT);

        //btnForgetPassword.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        btnForgetPassword.getPaint().setAntiAlias(true);//抗锯齿
//        btnRegister.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
//        btnRegister.getPaint().setAntiAlias(true);//抗锯齿


        api = WXAPIFactory.createWXAPI(this, "wxcd391c2ab8b96890", false);
        api.registerApp("wxcd391c2ab8b96890");
        mUnionId = "";

        mHandler = new LoginHandler(LoginActivity.this);
        btnVisible.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 显示密码
                        editPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        editPassword.postInvalidate();
                        //切换后将EditText光标置于末尾
                        CharSequence charSequence = editPassword.getText();
                        if (charSequence != null) {
                            Spannable spanText = (Spannable) charSequence;
                            Selection.setSelection(spanText, charSequence.length());
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        // 隐藏密码
                        editPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        editPassword.postInvalidate();
                        //切换后将EditText光标置于末尾
                        CharSequence charSequence1 = editPassword.getText();
                        if (charSequence1 != null) {
                            Spannable spanText = (Spannable) charSequence1;
                            Selection.setSelection(spanText, charSequence1.length());
                        }
                        break;
                }
                return true;
            }
        });
    }

    @OnClick({R.id.btn_login, R.id.btn_forget_password, R.id.btn_register,R.id.btn_wx_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                String mPhone = editAccount.getText().toString().trim();
                String mPassword = editPassword.getText().toString().trim();
                if (StringUtils.isMobile(mPhone)) {
                    if (mPassword.length() >= 6 && mPassword.length() <= 18 && !TextUtils.isEmpty(mUnionId)) {
                        mAppHelper.apiService().toLogin(mPhone, mPassword, mUnionId).enqueue(new BaseCallback<ApiResponse<LoginBean>>() {
                            @Override
                            public void onResponse(Call<ApiResponse<LoginBean>> call, Response<ApiResponse<LoginBean>> response) {
                                super.onResponse(call, response);
                                if(response.isSuccessful()&&!response.body().isSccessful()){
                                    new SVProgressHUD(mContext).showErrorWithStatus(response.body().getMsg());
                                    return;
                                }
                                new SVProgressHUD(mContext).showSuccessWithStatus("登录成功");
                                Session.setSessionKey(response.body().getData().getToken());
                                Session.setUserPhone(response.body().getData().getPhone());
                                Session.setUserIsLogin(true);
                                SignHelper.initToken(Session.getSessionKey());
                                activityStartUtils.skipActivity(MainActivity.class);
                            }

                            @Override
                            public void onFailure(Call<ApiResponse<LoginBean>> call, Throwable t) {
                                super.onFailure(call, t);
                                new SVProgressHUD(mContext).showSuccessWithStatus("请求失败");
                            }
                        });
                    } else if (mPassword.length() >= 6 && mPassword.length() <= 18 && TextUtils.isEmpty(mUnionId)) {
                        mAppHelper.apiService().toLogin(mPhone, mPassword).enqueue(new BaseCallback<ApiResponse<LoginBean>>() {
                            @Override
                            public void onResponse(Call<ApiResponse<LoginBean>> call, Response<ApiResponse<LoginBean>> response) {
                                super.onResponse(call, response);
                                if(response.isSuccessful()&&!response.body().isSccessful()){
                                    new SVProgressHUD(mContext).showErrorWithStatus(response.body().getMsg());
                                    return;
                                }
                                new SVProgressHUD(mContext).showSuccessWithStatus("登录成功");
                                Session.setSessionKey(response.body().getData().getToken());
                                Session.setUserPhone(response.body().getData().getPhone());
                                Session.setUserIsLogin(true);
                                SignHelper.initToken(Session.getSessionKey());
                                activityStartUtils.skipActivity(MainActivity.class);
                            }

                            @Override
                            public void onFailure(Call<ApiResponse<LoginBean>> call, Throwable t) {
                                super.onFailure(call, t);
                                new SVProgressHUD(mContext).showSuccessWithStatus("请求失败");
                            }
                        });
                    } else{
                        new SVProgressHUD(mContext).showErrorWithStatus(getString(R.string.password_error));
                    }
                } else {
                    new SVProgressHUD(mContext).showErrorWithStatus(getString(R.string.account_error));
                }
                break;
            case R.id.btn_forget_password:
                activityStartUtils.showActivity(ForgetPassWordActivity.class);
                break;
            case R.id.btn_register:
                activityStartUtils.showActivity(RegisterActivity.class);
                break;
            case R.id.btn_wx_login:
                wxLogin();


                break;
        }
    }

    private void wxLogin() {
        if(SystemUtils.isWeixinAvilible(mContext)){
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.transaction = "wxcd391c2ab8b96890";
            req.state = "wechat_sdk_gym_login";
            api.sendReq(req);

        }else {
            ToastUtil.show(mContext,R.string.ssdk_wechat_client_inavailable);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.e("Login_onActivityResult",String.valueOf(requestCode));
    }

    class LoginHandler extends Handler{
        private Context mContext;
        public LoginHandler(Context _context){
            this.mContext = _context;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    mUnionId = msg.obj.toString();
                    toLoginByWx(mUnionId);
                    break;
                case 1:

                    new AlertDialog.Builder(mContext)
                            .setTitle("提示")
                            .setMessage("检测到您尚未绑定微信，您可以：")
                            .setPositiveButton("注册新账号",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialoginterface, int i) {
                                            //
                                            dialoginterface.dismiss();
                                            Bundle bdl = new Bundle();
                                            bdl.putString("wx_id", mUnionId);
                                            activityStartUtils.showActivity((LoginActivity)mContext,RegisterActivity.class,bdl);
                                        }
                                    })
                            .setNegativeButton("绑定已有账号",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialoginterface, int i) {
                                            //
                                            dialoginterface.dismiss();
                                        }
                                    }).show();
                    break;
            }
        }
    }


    private void toLoginByWx(String wx_id) {
        mAppHelper.apiService().toLoginByWx(wx_id).enqueue(new BaseCallback<ApiResponse<LoginBean>>() {
            @Override
            public void onResponse(Call<ApiResponse<LoginBean>> call, Response<ApiResponse<LoginBean>> response) {
                super.onResponse(call, response);
                if(response.isSuccessful()&&!response.body().isSccessful()){
                    new SVProgressHUD(LoginActivity.this).showErrorWithStatus(response.body().getMsg());
                    return;
                }
                new SVProgressHUD(LoginActivity.this).showSuccessWithStatus("登录成功");
                Session.setSessionKey(response.body().getData().getToken());
                Session.setUserPhone(response.body().getData().getPhone());
                Session.setUserIsLogin(true);
                SignHelper.initToken(Session.getSessionKey());
                (new ActivityStartUtils(LoginActivity.this)).skipActivity(MainActivity.class);
            }

            @Override
            public void onFailure(Call<ApiResponse<LoginBean>> call,Throwable t) {
                super.onFailure(call,t);
                new SVProgressHUD(LoginActivity.this).showSuccessWithStatus("请求失败");
                Message msg = new Message();
                msg.what = 1;
                msg.obj = mUnionId;
                LoginActivity.mHandler.sendMessage(msg);
            }
        });


    }
}

